/*
 * Copyright 2013 NJUT  qixiaobo. All rights reserved.
 */
package com.fujitsu.nanjing.tieba.controller.post;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fujitsu.nanjing.tieba.base.BaseController;
import com.fujitsu.nanjing.tieba.common.Dialog;
import com.fujitsu.nanjing.tieba.common.ThirdVelocityEmailService;
import com.fujitsu.nanjing.tieba.exception.Resource404Exception;
import com.fujitsu.nanjing.tieba.ibator.CoreAttach;
import com.fujitsu.nanjing.tieba.ibator.CoreReply;
import com.fujitsu.nanjing.tieba.ibator.CoreTopic;
import com.fujitsu.nanjing.tieba.ibator.CoreUser;
import com.fujitsu.nanjing.tieba.service.AttachService;
import com.fujitsu.nanjing.tieba.service.BoardService;
import com.fujitsu.nanjing.tieba.service.ReplyService;
import com.fujitsu.nanjing.tieba.service.TopicService;
import com.fujitsu.nanjing.tieba.service.UserService;
import com.fujitsu.nanjing.tieba.struct.FileStruct;
import com.fujitsu.nanjing.tieba.view.velocity.tools.AuthTool;

/**
 * ReplyController.java
 * 
 * @author Administrator
 */
@Controller
@RequestMapping("/forum/boards")
public class ReplyController extends BaseController {
	@Resource
	private BoardService boardService;
	@Resource
	private TopicService topicService;
	@Resource
	private ReplyService replyService;
	@Resource
	private AttachService attachService;
	@Resource
	private ThirdVelocityEmailService thirdVelocityEmailService;
	@Resource
	private UserService userService;
	@RequestMapping(value = "/{boardid}/{topicId}", method = RequestMethod.GET)
	public String show(@PathVariable String boardid,
			@PathVariable String topicId, Model model, String titleHidden,
			String seqNo, String replyId, String type)
			throws Resource404Exception {
		checkTopic(boardid, topicId);
		topicId = decrypt(topicId);
		model.addAttribute("boardId", decrypt(boardid));
		model.addAttribute("replyTitle", titleHidden);
		model.addAttribute("topicId", topicId);
		model.addAttribute("type", "topic");
		int hiddenValue = 1;
		if (type != null && type.equals("edit")) {
			// 修改主題
			CoreTopic topic = topicService.findById(topicId);
			model.addAttribute("action", "edit");
			if (topic != null) {
				model.addAttribute("topic", topic);
				List<CoreAttach> attaches = attachService
						.getAllAttachesByTopicId(Integer.parseInt(topicId));
				model.addAttribute("attaches", attaches);
				if (attaches != null && attaches.size() > 0) {
					hiddenValue = attaches.get(attaches.size() - 1)
							.getLocalid() + 1;
				}

			}
		} else if (seqNo != null) {
			// 引用
			if (replyId.equals("0")) {
				// 主题
				CoreTopic topic = topicService.findById(topicId);
				if (topic != null) {
					model.addAttribute("quote", getQuote(topic, seqNo));
				}
			} else {
				// 回复
				CoreReply reply = replyService.findById(replyId);
				if (reply != null) {
					model.addAttribute("quote", getQuote(reply, seqNo));
				}
			}
			model.addAttribute("action", "post");

		} else {
			model.addAttribute("action", "post");
		}
		model.addAttribute("dialog", Dialog.instance().setContent(getContent()));
		model.addAttribute("hiddenValue", hiddenValue);
		return "reply/reply";
	}

	private String getQuote(CoreTopic topic, String seqNo) {
		StringBuilder sb = new StringBuilder();
		sb.append(" <br><div class='quote'><h5>引用:</h5><blockquote>");
		sb.append(topic.getTitle());
		sb.append("<p class='quotefooter'>--- <a href=/topics/");
		sb.append(encrypt(topic.getTopicid().toString()));
		sb.append(">原帖序号:");
		sb.append(seqNo);
		sb.append("#</a>,&nbsp; 由<a href='/forum/members/");
		sb.append(topic.getUserid());
		sb.append("'><i>");
		sb.append(topic.getNickname());
		sb.append("</i></a>于");
		sb.append(format(topic.getCreatetime()));
		sb.append("&nbsp;发表</p></blockquote></div><br>");
		return sb.toString();
	}

	private String getQuote(CoreReply reply, String seqNo) {
		StringBuilder sb = new StringBuilder();
		sb.append(" <br><div class='quote'><h5>引用:</h5><blockquote>");
		sb.append(reply.getTitle());
		sb.append("<p class='quotefooter'>--- <a href=/topics/");
		sb.append(encrypt(reply.getTopicid().toString()));
		sb.append("/");
		sb.append(encrypt(reply.getReplyid().toString()));
		sb.append(">原帖序号:");
		sb.append(seqNo);
		sb.append("#</a>,&nbsp; 由<a href='/forum/members/" + reply.getUserid()
				+ "'><i>");
		sb.append(new AuthTool().getUserName(reply.getUserid()));
		sb.append("</i></a>于");
		sb.append(format(reply.getCreatetime()));
		sb.append("&nbsp;发表</p></blockquote></div><br>");
		return sb.toString();
	}

	@RequestMapping(value = "/{boardid}/{topicId}/{replyId}", method = RequestMethod.GET)
	public String show(@PathVariable String boardid,
			@PathVariable String topicId, @PathVariable String replyId,
			Model model, String titleHidden, String type)
			throws Resource404Exception {
		checkReply(boardid, topicId, replyId);
		boardid = decrypt(boardid);
		topicId = decrypt(topicId);
		replyId = decrypt(replyId);
		model.addAttribute("replyTitle", titleHidden);
		model.addAttribute("boardId", boardid);
		model.addAttribute("topicId", topicId);
		model.addAttribute("replyId", replyId);
		model.addAttribute("type", "reply");
		int hiddenValue = 1;
		if (type != null && type.equals("edit")) {
			// 修改主題
			CoreReply reply = replyService.findById(replyId);
			model.addAttribute("action", "edit");
			if (reply != null) {
				model.addAttribute("reply", reply);
				List<CoreAttach> attaches = attachService
						.getAllAttachesByReplyId(Integer.parseInt(replyId));
				model.addAttribute("attaches", attaches);
				if (attaches != null && attaches.size() > 0) {
					hiddenValue = attaches.get(attaches.size() - 1)
							.getLocalid() + 1;
				}

			}
		} else {
			model.addAttribute("action", "post");
		}
		model.addAttribute("hiddenValue", hiddenValue);
		model.addAttribute("dialog", Dialog.instance().setContent(getContent()));
		return "reply/reply";
	}
	@RequestMapping(value = "/{boardid}/{topicId}/{replyId}", method = RequestMethod.DELETE)
	public String delete(@PathVariable String boardid,
			@PathVariable String topicId, @PathVariable String replyId)
			throws Resource404Exception {
		replyService.delete(checkReply(boardid, topicId, replyId));
		return redirect("/topics/" + topicId);
	}
	@RequestMapping(value = {"/{boardid}/{topicId}"}, method = RequestMethod.POST)
	public String create(@PathVariable String boardid,
			@PathVariable String topicId, Model model,
			MultipartHttpServletRequest mhsRequest, CoreReply reply,
			String post, String subject, HttpSession session)
			throws Resource404Exception {
		checkTopic(boardid, topicId);
		topicId = decrypt(topicId);
		CoreTopic topic = topicService.findById(topicId);

		Map<String, MultipartFile> files = mhsRequest.getFileMap();
		List<FileStruct> fileStructs = initFileStruct(files, mhsRequest);
		initWebRoot();
		reply.setTopicid(Integer.parseInt(topicId));
		reply.setTitle(filterWord(subject));
		reply.setContent(filterWord(post));
		reply.setUserid(session.getAttribute(USERID).toString());
		reply.setRemoteip(mhsRequest.getRemoteAddr());
		reply.setAttaches((byte) fileStructs.size());
		int replyid = replyService.insertWithAttaches(reply, fileStructs);
		topicService.addReplies(topicId);
		String url = "/topics/" + encrypt(topicId) + "/"
				+ encrypt(String.valueOf(replyid));
		CoreUser user = userService.findById(topic.getUserid());
		String[] emails = new String[]{};
		if (user != null) {
			emails = new String[]{user.getEmail()};
		}
		if (topic.getIsreplynotice().equals("T")) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("url", url);
			map.put("reply", reply);
			thirdVelocityEmailService.sendEmail(map, "您的主题【" + topic.getTitle()
					+ "】有新回复了", "com/fujitsu/mailTemplates/reply.vm", emails,
					new String[]{});
		}

		return redirect(url);
	}
	@RequestMapping(value = "/{boardid}/{topicId}/edit", method = RequestMethod.POST)
	public String edit(@PathVariable String boardid,
			@PathVariable String topicId, Model model,
			MultipartHttpServletRequest mhsRequest, CoreTopic topic,
			String post, String subject, HttpSession session)
			throws Resource404Exception {
		checkTopic(boardid, topicId);
		topicId = decrypt(topicId);
		Map<String, MultipartFile> files = mhsRequest.getFileMap();
		List<FileStruct> fileStructs = initFileStruct(files, mhsRequest);
		initWebRoot();
		if (topic.getTopscope() == null) {
			topic.setTopscope("N");
		}
		if (topic.getIshidepost() == null) {
			topic.setIshidepost("F");
		}
		if (topic.getIsreplynotice() == null) {
			topic.setIsreplynotice("F");
		}
		topic.setTopicid(Integer.parseInt(topicId));
		topic.setTitle(subject);
		topic.setContent(post);
		topic.setUserid(session.getAttribute(USERID).toString());
		topic.setRemoteip(mhsRequest.getRemoteAddr());
		topic.setAttaches((byte) fileStructs.size());
		if (fileStructs.size() > 0) {
			topic.setAttachicon("A");
		}
		checkPicture(topic);
		topicService.updateWithAttaches(topic, fileStructs);
		return redirect("/topics/" + encrypt(topicId));
	}
	@RequestMapping(value = "/{boardid}/{topicId}/{replyId}/edit", method = RequestMethod.POST)
	public String edit(@PathVariable String boardid,
			@PathVariable String topicId, @PathVariable String replyId,
			Model model, MultipartHttpServletRequest mhsRequest,
			CoreReply reply, String post, String subject, HttpSession session)
			throws Resource404Exception {
		checkReply(boardid, topicId, replyId);
		topicId = decrypt(topicId);
		replyId = decrypt(replyId);
		boardid = decrypt(boardid);
		model.addAttribute("boardId", boardid);
		Map<String, MultipartFile> files = mhsRequest.getFileMap();
		List<FileStruct> fileStructs = initFileStruct(files, mhsRequest);
		initWebRoot();
		reply.setTopicid(Integer.parseInt(topicId));
		reply.setReplyid(Integer.parseInt(replyId));
		reply.setTitle(subject);
		reply.setContent(post);
		if (reply.getIshidepost() == null) {
			reply.setIshidepost("F");
		}
		reply.setUserid(session.getAttribute(USERID).toString());
		reply.setRemoteip(mhsRequest.getRemoteAddr());
		reply.setAttaches((byte) fileStructs.size());
		replyService.updateWithAttaches(reply, fileStructs);
		return redirect("/topics/" + encrypt(topicId) + "/#rid" + replyId);

	}
	@RequestMapping(value = "/{boardid}/{topicId}/{replyId}", method = RequestMethod.POST)
	public String create(@PathVariable String boardid,
			@PathVariable String topicId, @PathVariable String replyId,
			Model model, MultipartHttpServletRequest mhsRequest,
			CoreReply reply, String post, String subject, HttpSession session)
			throws Resource404Exception {
		checkReply(boardid, topicId, replyId);
		topicId = decrypt(topicId);
		replyId = decrypt(replyId);
		boardid = decrypt(boardid);
		model.addAttribute("boardId", boardid);
		Map<String, MultipartFile> files = mhsRequest.getFileMap();
		List<FileStruct> fileStructs = initFileStruct(files, mhsRequest);
		initWebRoot();
		reply.setTopicid(Integer.parseInt(topicId));
		reply.setReplyid(Integer.parseInt(replyId));
		reply.setTitle(filterWord(subject));
		reply.setContent(filterWord(post));
		reply.setUserid(session.getAttribute(USERID).toString());
		reply.setRemoteip(mhsRequest.getRemoteAddr());
		reply.setAttaches((byte) fileStructs.size());
		replyService.insertWithAttaches(reply, fileStructs);
		topicService.addReplies(topicId);
		return redirect("/topics/" + encrypt(topicId) + "/999");
	}
	public void checkTopic(String boardid, String topicId)
			throws Resource404Exception {
		boardid = decrypt(boardid);
		topicId = decrypt(topicId);

		if (boardService.findById(boardid) == null) {
			throw new Resource404Exception("该板块不存在！");
		}
		if (topicService.findById(topicId) == null) {
			throw new Resource404Exception("该主题不存在！");
		}
	}
	public CoreReply checkReply(String boardid, String topicId, String replyId)
			throws Resource404Exception {
		checkTopic(boardid, topicId);
		replyId = decrypt(replyId);
		CoreReply reply = replyService.findById(replyId);
		if (reply == null) {
			throw new Resource404Exception("该回复不存在！");
		}
		return reply;
	}
	/** 将表单域里的相关加入数据结构中 */
	public List<FileStruct> initFileStruct(Map<String, MultipartFile> files,
			MultipartHttpServletRequest request) {
		List<FileStruct> fileStructs = new ArrayList<FileStruct>();
		FileStruct fileStruct = null;
		for (Entry<String, MultipartFile> file : files.entrySet()) {
			fileStruct = new FileStruct();
			if (file.getValue() == null || file.getValue().getSize() == 0) {
				continue;
			}
			String[] args = file.getKey().split("_");
			int localId = Integer.parseInt(args[1]);
			fileStruct.setFile(file.getValue());
			int credits = Integer.parseInt(request
					.getParameter("attachcredits_" + localId));
			fileStruct.setCredits(credits);
			String title = request.getParameter("attachtitle_" + localId);
			fileStruct.setTitle(title);
			fileStruct.setLocalid(localId);
			fileStructs.add(fileStruct);
		}
		return fileStructs;

	}
	private void checkPicture(CoreTopic topic) {
		if (topic.getContent().toLowerCase().contains("<img")) {
			topic.setAttachicon("I");
		}

	}
}
